package com.mnt.washio.activities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Base64;
import android.util.Log;

import com.mnt.washio.R;
import com.parse.ParseUser;

public class SplashActivity extends Activity {
	private boolean cancel = false;
	private SharedPreferences pref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_splash);

		initView();

//		getKeyHash();
	}

	private void getKeyHash() {
		try {

			PackageInfo info = getPackageManager().getPackageInfo(
					getPackageName(), PackageManager.GET_SIGNATURES);

			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.d("KeyHash:",
						Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}

		} catch (NameNotFoundException e) {
			Log.e("name not found", e.toString());
		} catch (NoSuchAlgorithmException e) {
			Log.e("no such an algorithm", e.toString());
		}
	}

	private void initView() {
		pref = getSharedPreferences("MNT_WASHIO", MODE_PRIVATE);

		new CountDownTimer(2000, 1000) {

			@Override
			public void onTick(long millisUntilFinished) {

			}

			@Override
			public void onFinish() {
				if (!cancel) {
					Intent i = new Intent();
					if (pref.getBoolean("FIRST_LAUNCH", true)) {

						i.putExtra("FROM_SPLASH", true);
						i.setClass(SplashActivity.this,
								WalkThroughActivity.class);
					} else {
						if (ParseUser.getCurrentUser().getObjectId() != null
								&& ParseUser.getCurrentUser().getEmail() != null) {
							i.setClass(SplashActivity.this, MainActivity.class);
						} else {
							i.setClass(SplashActivity.this, LoginActivity.class);
						}
					}

					startActivity(i);
					finish();
				}

			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		cancel = true;
		super.onBackPressed();
	}

}
